package com.timon.sla;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import com.komon.api.InternalContainer;
import com.komon.exception.RequestFormatErroException;
import com.komon.exception.StatusCodeExceptoin;
import com.komon.factory.ResponseFactory;
import com.komon.object.OneRequestContext;
import com.komon.object.request.InternalHttpRequest;
import com.komon.object.request.SimpleHttpRequest;
import com.komon.object.response.HttpResponse;
import com.komon.parser.HttpRequestParser;

public class Server {
	private static HttpRequestParser parser = new HttpRequestParser();
	private static InternalContainer container = new InternalContainer();
	
	public static void main(String[] args) throws IOException,
			ClassNotFoundException, InterruptedException {
		int timeout = 9000;
		ServerSocket server = new ServerSocket(8080);
		
		boolean connectionClose = true;
		Socket socket;
		while(true){
			socket = server.accept();
			//socket.setSoTimeout(timeout);
			
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			while(!connectionClose) {
					SimpleHttpRequest request = null;
					InternalHttpRequest internalRequest = null;
					
					HttpResponse response = null;
					OneRequestContext context = new OneRequestContext();
					try {
						request = parser.parseNextRequest(in, context);
						internalRequest = new InternalHttpRequest(request);
						//TODO
						//if no exceptions, we use 200 OK as default status of response
						response = ResponseFactory.creatResponseByStatus(200, out);
						//servlet container 
						container.service(internalRequest, response);
					} catch (RequestFormatErroException e) {
						//TODO
						e.printStackTrace();
					} catch (SocketTimeoutException e) {
						e.printStackTrace();
						connectionClose = true;
					} catch (StatusCodeExceptoin e) {
						e.printStackTrace();
					} catch (Exception e){
						e.printStackTrace();
						//unknown error
						response = ResponseFactory.creatResponseByStatus(400, out);
					} finally{
						internalRequest.skipCurrentRequest();
						//flush all buffer and output the end of the this response
						response.close();
						//TODO
						if (internalRequest.isConnectionClosed()) {
							connectionClose = false;
						}
					/*	String resp = "HTTP/1.1 200 \r\nContent-Length:2\r\nDate:Thu, 18 Mar 2010 11:23:36 GMT\r\naa\r\n";
						Writer w = new PrintWriter(new OutputStreamWriter(out));
						w.write(resp);
						w.flush();*/
						//TODO release context
						context = null;
					}
			}
			socket.close();
		}
	}
}
